package com.service.mujuan;

import com.bean.AutoOriginPaperBean;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.model.*;
import com.utils.ConstData;

import java.util.*;

/**
 * Created by Hexun on 2017/6/22 0022.
 */
public class MujuanService {
    private static int paperTurn = 0;

    /**
     * @Author:HeXun
     * @Description: 获取组卷细节，各题型题目题数等
     * @Date: 2017/6/22 0022
     */
    public List getZujuanDetail(int courseId) throws Exception {
        /*String[] type = {"CHOICE", "JUDGE", "SIMPLEFILL", "CHOICEREAD",
                "SIMPLEPRESS", "PROGRAM", "CHOICEFILL", "COMPLEXFILL"};
        */
        int type[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        List<AutoOriginPaperBean> finalList = new ArrayList<AutoOriginPaperBean>();
        ConstData constData = new ConstData();
        for (int i = 0; i < type.length; i++) {
            List<Record> chapter = getAutoZuJuanChapter(courseId, constData.ques_Map.get(type[i]).toString());// 得到题库中有哪些章节
            if (chapter == null) {
                continue;
            }
            if (chapter.size() <= 0) {
                continue;// 若章节为0则经行下一次循环
            }
            for (Record cp : chapter) {// 得到所有的章节，用章节过滤一下
                if (cp.get("chapter") == null) {//判断是否为空,否则会抛出Integer转化异常
                    continue;
                }
                String chapterTemp = cp.get("chapter").toString();
                if (chapterTemp == "" || "".equals(chapterTemp)) {
                    continue;
                }
                List<Record> rate = getAutoZuJuanRate(courseId, constData.ques_Map.get(type[i]).toString(), chapterTemp);
                if (rate == null) {
                    continue;
                }
                for (Record rt : rate) {// 确定章节，用难度系数过滤一下
                    Integer rateTemp = rt.get("rate");
                    if (rateTemp == null) {
                        continue;
                    }
                    List<Record> point = getAutoZuJuanPoint(courseId,
                            chapterTemp, rateTemp.intValue(), constData.ques_Map.get(type[i]).toString());
                    if (point == null) {
                        continue;
                    }
                    for (Record po : point) {// 确定章节、难度系数，用知识点过滤，但是知识点全是空的。。。
                        if (po.get("point") == null) continue;
                        String idTemp = po.get("point").toString();
                        if (idTemp == null || "".equals(idTemp)) {
                            continue;
                        }
                        List<Record> detail = getAutoZuJuan(courseId,
                                chapterTemp, rateTemp, (String) constData.ques_Map.get(type[i]),
                                idTemp);
                        AutoOriginPaperBean ab = new AutoOriginPaperBean(detail, courseId, chapterTemp, rateTemp, type[i], idTemp);
                        finalList.add(ab);
                    }
                }
            }
        }
        return finalList;
    }


    public List<Record> getAutoZuJuanChapter(int courseID, String type) {
        String sql = "select distinct chapter from " + type + " where course_id='" + courseID + "' order by chapter";
        return Db.find(sql);
    }

    public List<Record> getAutoZuJuanRate(int courseID, String type, String chapter) {
        String sql = "select distinct rate from " + type + " where course_id='"
                + courseID + "' and chapter='" + chapter + "' order by rate";
        return Db.find(sql);
    }

    public List<Record> getAutoZuJuanPoint(int courseID, String chapter, int rateTemp,
                                           String type) {
        String sql = "select distinct point from " + type + " where course_id='" + courseID + "' and chapter = '" + chapter + "'  order by point";
        return Db.find(sql);
    }

    public List<Record> getAutoZuJuan(int courseID, String chapter, int rate,
                                      String type, String point) {
        String sql = "select id from " + type + " where course_id ='"
                + courseID + "' and chapter='" + chapter + "' and rate=" + rate
                + " and point = '" + point + "' order by id ";
        return Db.find(sql);
    }

    public boolean doAutoZujuan(List<AutoOriginPaperBean> courseDetail, String[] giveNumbers, String courseID, int changCi) {
        try {
            for (int i = 0; i < changCi; i++) {
                PaperConfig pc = new PaperConfig().set("course_id", courseID).set("exam_no", i + 1);
                pc.save();
                for (int j = 0; j < giveNumbers.length; j++) {
                    if (Integer.parseInt(giveNumbers[j]) == 0) {
                        continue;
                    }
                    if (courseDetail == null || courseDetail.size() <= 0) {
                        continue;
                    }
                    AutoOriginPaperBean autoOriginPaperBean = courseDetail.get(j);
                    List<Record> questionId = autoOriginPaperBean.getQuestionID();
                    List num = getRandom(questionId.size());
                    if (num.size() == 0) {
                        continue;
                    } else {
                        for (int i2 = 0; i2 < num.size() && i2 < Integer.parseInt(giveNumbers[j]); i2++) {
                            String question_id = questionId.get(((Integer) num.get(i2)).intValue()).get("id").toString();
                            OriginPaper op = new OriginPaper();
                            op.set("paperconfig_id", pc.get("id")).set("ques_id", question_id).set("ques_type", autoOriginPaperBean.getType()).set("ques_sq", ++paperTurn);
                            op.save();
                        }
                    }
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public List<Integer> getRandom(int num) {
        List<Integer> numList = new ArrayList<Integer>();
        for (int i = 0; i < num; i++) {
            numList.add(new Integer(i));
        }
        Collections.shuffle(numList);
        return numList;
    }

    /**
     * @Author:HeXun
     * @Description: 获得母卷的所有题目
     * @Date: 2017/6/25 0025
     */
    public List getOriginPaperQuestions(Course course, int changci, String examPlace, int questionType) {
        List<PaperConfig> list = PaperConfig.dao.find("select * from paperconfig where course_id=? and exam_no=? ", course.get("id"), changci);
        if (list != null && list.size() > 0) {
            PaperConfig paperConfig = list.get(0);
            if (paperConfig != null) {
                return getQuestionsByConfigAndType(paperConfig, questionType);
            }
        }
        return null;
    }

    public List getQuestionsByConfigAndType(PaperConfig paperConfig, int type) {
        List<OriginPaper> question = OriginPaper.dao.find("select * from originpaper where paperconfig_id=? and ques_type=?", paperConfig.get("id"), type);
        List list = new ArrayList();
        for (int i = 0; i < question.size(); i++) {
            switch (type) {
                case ConstData.CHOICE:
                    Choice choice = Choice.dao.findById(question.get(i).get("ques_id"));
                    list.add(choice);
                    break;
                case ConstData.JUDGE:
                    Judge judge = Judge.dao.findById(question.get(i).get("ques_id"));
                    list.add(judge);
                    break;
                case ConstData.SIMPLE_FILL:
                    SimpleFill simpleFill = SimpleFill.dao.findById(question.get(i).get("ques_id"));
                    list.add(simpleFill);
                    break;
                case ConstData.COMPLEX_FILL:
                    ComplexFill complexFill = ComplexFill.dao.findById(question.get(i).get("ques_id"));
                    list.add(complexFill);
                    break;
                case ConstData.SIMPlE_PRESS:
                    SimplePress simplePress = SimplePress.dao.findById(question.get(i).get("ques_id"));
                    list.add(simplePress);
                    break;
                case ConstData.PROGRAM:
                    Program program = Program.dao.findById(question.get(i).get("ques_id"));
                    list.add(program);
                    break;
                case ConstData.CHOICE_FILL:
                    ChoiceFill choiceFill = ChoiceFill.dao.findById(question.get(i).get("ques_id"));
                    list.add(choiceFill);
                    break;
                case ConstData.GONGWENXIEZUO:
                    Gongwenxiezuo gongwenxiezuo = Gongwenxiezuo.dao.findById(question.get(i).get("ques_id"));
                    list.add(gongwenxiezuo);
                    break;
                case ConstData.CHOICEREAD:
                    ChoiceRead choiceRead = ChoiceRead.dao.findById(question.get(i).get("ques_id"));
                    list.add(choiceRead);
                    break;
            }
        }
        return list;
    }

    public List getQuestions(String type, String rate, String courseId) {
        List questions = Db.find("select * from " + ConstData.getTimuName(Integer.parseInt(type)) + " where rate =? and course_id=? and id not in (select ques_id from originpaper where ques_type=?)", rate, courseId, type);
        return questions;
    }

    //获取一键组卷的年级
    public List<String> getGrades() {
        Set<String> set = new HashSet<String>();//为了去重
        List<Course> courseList = Course.dao.find("select * from courses");
        for (Course course : courseList) {
            String grade = course.get("name").toString().substring(0, course.get("name").toString().indexOf("-"));
            set.add(grade);
        }
        List<String> gradeList = new ArrayList<String>(set);
        return gradeList;
    }

    //获取科目的套题,当前版本为章节
    public List<Integer> getTaoti(int courseId) {
        String[] type = {"choice", "judge", "simplefill", "choiceread",
                "simplepress", "program", "choicefill", "complexfill"};
        Set<Integer> chapterSet = new HashSet<Integer>();
        for (int i = 0; i < type.length; i++) {
            List<Record> list = Db.find("select distinct chapter from " + type[i] + " where course_id=? order by chapter", courseId);
            for (Record r : list) {
                chapterSet.add( Integer.parseInt(String.valueOf(r.get("chapter"))));

            }
        }
        List<Integer> chapters = new ArrayList<Integer>(chapterSet);
        Collections.sort(chapters);
        return chapters;
    }

    public boolean simpleZujuan(int courseId, int courseChapter) {
        Course course = Course.dao.findById(String.valueOf(courseId));
        PaperConfig pc = new PaperConfig();
        pc.set("course_id", courseId).set("exam_no", 1).set("room", "").save();
        String[] type = {"choice", "judge", "simplefill", "choiceread",
                "simplepress", "program", "choicefill", "complexfill"};
        List num = null;
        List<Record> questionList = null;
        for (int i = 0; i < type.length; i++) {
            questionList = getQueByTypeAndCourse(
                    courseId, type[i], courseChapter);
            num = getRandom(questionList.size());
            if (num.size() <= 0) {
                continue;
            } else {
                for (int j = 0; j < num.size() && j < questionList.size(); j++) {
                    String question_id = (questionList
                            .get((Integer) num.get(j))).get("id") + "";
                    OriginPaper op = new OriginPaper();
                    op.set("paperconfig_id", pc.get("id"));
                    op.set("ques_id", question_id);
                    op.set("ques_type", ConstData.getTypeInt(type[i]));
                    op.set("ques_sq", ++paperTurn);
                    op.save();
                }
            }
        }
        return true;
    }

    public List<Record> getQueByTypeAndCourse(int course_id, String type, int chapter) {
        List<Record> list = Db.find("select * from " + type + " where course_id = ? and chapter =?", course_id, chapter);
        return list;
    }


}
